<?php

header("Content-type: application/json");
/*
 * 广告机的Action
*
*/
define('MAX_SCENEID', 100000);
define('QR_EXPIRE_SECONDS', 1800);
define('QR_SCENE', 'QR_SCENE');	// 临时二维码
define('QR_LIMIT_SCENE', 'QR_LIMIT_SCENE'); // 永久二维码
define('QR_LIMIT_STR_SCENE',"QR_LIMIT_STR_SCENE");
class QRCodeAction extends Action {
	 /**
    * 导出数据为excel表格
    *@param $id    需要导出的二维码id号 多个逗号分隔
    *@param $title   excel的第一行标题,一个数组,如果为空则没有标题
    *@param $filename 下载的文件名
    *@examlpe 
    $stu = M ('User');
    $arr = $stu -> select();
    exportexcel($arr,array('id','账户','密码','昵称'),'文件名!');
*/
	public function exportexcel($id='',$title=array('二维码编号','类型','名称','关键字','扫描次数','二维码图片'),$filename='qrcode'){
		header("Content-type:application/octet-stream");
		header("Accept-Ranges:bytes");
		header("Content-type:application/vnd.ms-excel");  
		header("Content-Disposition:attachment;filename=".$filename.".xls");
		header("Pragma: no-cache");
		header("Expires: 0");
		//导出xls 开始
		if (!empty($title)){
			foreach ($title as $k => $v) {
				$title[$k]=iconv("UTF-8", "UTF-8",$v);
			}
			$title= implode("\t", $title);
			echo "$title\n";
		}
		if (!empty($data)){
        foreach($data as $key=>$val){
            foreach ($val as $ck => $cv) {
                $data[$key][$ck]=iconv("UTF-8", "UTF-8", $cv);
            }
            $data[$key]=implode("\t", $data[$key]);
            
        }
        echo implode("\n",$data);
    }
}
	public function index($order = "updateTime", $orderBy = "desc", $start = 0, $limit = 25,
		$sceneId='',$name='',$actionInfo='',$module='',$startDate='', $endDate='') {
			
		$QRModel = M("qrcode");
		$qrcodescan = M("qrcode_scan_log");
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		
		$where["actionName"] = array(array("eq",QR_LIMIT_SCENE),array("eq",QR_LIMIT_STR_SCENE),'or');
		$where["qr.fromCustomerId"] = Session::$user["customerId"];
		$where["deleted"] = 0;
		!empty($sceneId) ?  $where['sceneId'] =$sceneId: "";
		!empty($name)  ? $where['name'] = array('like', '%'.$name.'%'): "";
		!empty($actionInfo) ? $where['actionInfo'] = array('like', '%'.$actionInfo.'%'): "";
		!empty($module)  ? $where['module'] =$module: "";
		if($startDate!='' && $endDate!=''){					
				$scanwhere["createTime"] = array("between","$startDate,$endDate");				
		}else if($startDate!='' && $endDate==''){
				$scanwhere["createTime"] = array("egt","$startDate");
		}else if($startDate=='' && $endDate!=''){
				$scanwhere["createTime"] = array("elt","$endDate");
		}
		if(!empty($scanwhere)){
	 		$sceneIds=$qrcodescan->distinct(true)->field("sceneId")->where($scanwhere)->select();
						$sceneIdsWhere='';
					 foreach($sceneIds as $key=>$value){							
								$sceneIdsWhere.=$value['sceneId'].',';
							}						
					$sceneIdsWhere = substr($sceneIdsWhere,0,strlen($sceneIdsWhere)-1);
			$where['sceneId'] = array('in',$sceneIdsWhere); 
		}
		
		$arr = $QRModel->alias("qr")->field("qr.*,tpye.typename")		
		->join("wx_qrcode_type tpye ON qr.module = tpye.id")->where($where)->order("$order $orderBy")->limit("$start, $limit")->select();
		if ($arr) {
			$count = $QRModel->alias("qr")->where($where)->count();
			Output::instance()->objArray($arr,$count);
		} else {
			Output::instance()->resultCode();
		}
	}
	
	/*
	 * 添加二维码，
	 * 永久二维码，如果是sceneId重复则覆盖，如果不希望覆盖通过调用isQRCodeSceneIdExist接口判断是否已经存在相同sceneId
	 * 临时二维码，则sceneId使用当前临时sceneId最大值
	 */
	public function add($sceneId, $name, $actionName, $actionInfo, $module, $accessTag) {
		if ($actionName == QR_LIMIT_SCENE && ($sceneId <= 0 || $sceneId > MAX_SCENEID)) {
			Output::instance()->resultCode(code_qr_scene_invalid);
			return;
		}
		$retVal = Session::init();
		
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}		
		if(!empty($accessTag)){			
			addAccessTags($accessTag);
		}
		$result = $this->addAfterSessionInit( $sceneId, $name, $actionName, $actionInfo, $module, $accessTag);
		if ($result) {
			$data["id"] = $result;
			Output::instance()->object($data);
		}
	}
	
	/*
	 * 批量添加二维码，
	 * $count 批量生成二维码个数
	 * $startSceneId 起始id
	* 永久二维码，如果是sceneId重复则覆盖，如果不希望覆盖通过调用isQRCodeSceneIdExist接口判断是否已经存在相同sceneId
	* 临时二维码，则sceneId使用当前临时sceneId最大值
	*/
	public function addBatch($count, $startSceneId, $name, $actionName, $actionInfo, $module, $accessTag) {
		if ($actionName == QR_LIMIT_SCENE && ($startSceneId <= 0 || $startSceneId > MAX_SCENEID)) {
			Output::instance()->resultCode(code_qr_scene_invalid);
			return;
		}
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		for ($i = 0; $i < $count; $i++) {
			$sceneId = $startSceneId + $i;
			if ($sceneId > MAX_SCENEID) {
				$count = $count - (MAX_SCENEID - $startSceneId + 1);
				$i = 0;
				$startSceneId = 1;
				$sceneId = 1;
			}
			$result = $this->addAfterSessionInit( $sceneId, $name, $actionName, $actionInfo, $module, $accessTag);
			//Output::instance()->Object($result);
			if ($result === FALSE) {
				return;
			}
		}
		if (!$result) {
			Output::instance()->resultCode(code_sql_error);
			return;
		}else{
			Output::instance()->resultCode(code_success);				
		}
		//Output::instance()->resultCode();
	}
	
	public function addAfterSessionInit($sceneId, $name, $actionName, $actionInfo, $module, $accessTag, $moduleId = NULL) {
		$customerId = Session::$user["customerId"];
		Session::switchCustomer(0);
		
		if ($actionName == QR_SCENE && empty($sceneId)) {
			$sceneId = $this->getMaxNotLimitSceneId($customerId);
		}
		
		Session::switchCustomer($customerId);
		$qrcode = $this->createQRCode($actionName, $sceneId);
		if ($qrcode == NULL) {
			return;
		}
		Session::switchCustomer(0);
		
		$QRModel = M("qrcode");
		//sceneId已经存在则重置
		$isDelete = $this->resetOldSceneId('',$customerId, $actionName, $sceneId);
		
		$data["fromCustomerId"] = $customerId;
		$data["sceneId"] = $sceneId;
		$data["name"] = $name;
		$data["actionName"] = $actionName;
		$data["actionInfo"] = $actionInfo;
		$data["module"] = $module;
		if ($moduleId != NULL) {
			$data["moduleId"] = $moduleId;
		}
		$data["accessTag"] =  $accessTag;
		$data["updateTime"] = date("Y-m-d H:i:s");
		$data["deleted"] = 0;
		$data["ticket"] = $qrcode->ticket;
		$result = $QRModel->add($data);
		Session::switchCustomer($customerId);
		if (!$result) {
			Output::instance()->resultCode(code_sql_error);
			return;
		}
		return $result;
	}
	
	/*
	 * 更新二维码，如果sceneId重复则覆盖，如果不希望覆盖通过调用isQRCodeSceneIdExist接口判断是否已经存在相同sceneId
	*/
	public function update($id, $sceneId, $name, $actionName, $actionInfo, $module, $accessTag) {
		if ($actionName == QR_LIMIT_SCENE && ($sceneId <= 0 || $sceneId > MAX_SCENEID)) {
			Output::instance()->resultCode(code_qr_scene_invalid);
			return;
		}
		
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		if(!empty($accessTag)){			
			addAccessTags($accessTag);
		}
//		$qrcode = $this->createQRCode($actionName, $sceneId);
//		if ($qrcode == NULL) {
//			return;
//		}
		$customerId = Session::$user["customerId"];
		Session::switchCustomer(0);
		
		//sceneId已经存在则重置
		$isDelete = $this->resetOldSceneId($id, $customerId, $actionName, $sceneId);
		
		$QRModel = M("qrcode");
		$data["sceneId"] = $sceneId;
		$data["name"] = $name;
		$data["actionName"] = $actionName;
		$data["actionInfo"] = $actionInfo;
		$data["accessTag"] =  $accessTag;
		
		$data["updateTime"] = date("Y-m-d H:i:s");
		$result = $QRModel->where("id=$id")->save($data);
		if ($result) {
			$data["id"] = $id;
			Output::instance()->object($data);
		} else {
			Output::instance()->resultCode(code_sql_error);
		}
		
		Session::switchCustomer($customerId);
	}
	
	/*
	 * id可以支持多个删除多个用,分割，由于ext后台还有人使用暂未修改参数名为ids
	 */
	public function delete($id) {
		
		$QRModel = M("qrcode");
		$QRLogModel = M("qrcode_scan_log");
		
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}

		$customerId = Session::$user["customerId"];
		$idArray = explode(",",$id);
		$where['id'] = array('in',$idArray);
		
		$result = $QRModel->where($where)->setField('deleted', 1);
		if ($result != false) {
			$qrArr = $QRModel->where($where)->field('actionName,sceneId')->select();
			foreach( $qrArr as $qr) {
				if ($qr["actionName"] == QR_LIMIT_SCENE) {
					$condition["sceneId"] = $qr["sceneId"];
					$condition["fromCustomerId"] = $customerId;
					$QRLogModel->where($condition)->delete();
				}
			}
			
			Output::instance()->resultCode();
		} else {
			Output::instance()->resultCode(code_sql_error);
		}
	}

	public function isQRCodeSceneIdExist($id, $actionName, $sceneId) {
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		
		$customerId = Session::$user["customerId"];
		Session::switchCustomer(0);
		
		$QRModel = M("qrcode");
		
		if ($id != '') {
			$where['id']  = array('neq',$id);
		}
		$where["deleted"] = 0;
		$where["fromCustomerId"] = $customerId;
		$where["sceneId"] = $sceneId;
		$where["actionName"] = $actionName;
		$result = $QRModel->where($where)->find();
		if ($result) {
			Output::instance()->resultCode(code_qr_scene_exist);
		} else {
			Output::instance()->resultCode();
		}
		
		Session::switchCustomer($customerId);
	}
	
	/*
	 * 将已经存在sceneId的数据删除并重置sceneId为NULL
	 */
	private function resetOldSceneId($id, $customerId, $actionName, $sceneId) {
		$QRModel = M("qrcode");
		if ($id != '') {
			$where['id']  = array('neq',$id);
		}
		$where["fromCustomerId"] = $customerId;
		$where["sceneId"] = $sceneId;
		$where["actionName"] = $actionName;
		$result = $QRModel->where($where)->find();
		if ($result) {
			$data["sceneId"] = NULL;
			$data["deleted"] = 1;
			$QRModel->where($where)->save($data);
			if ($actionName == QR_LIMIT_SCENE) {
				$LogModel = M("qrcode_log");
				$condition["fromCustomerId"] = $customerId;
				$condition["sceneId"] = $sceneId;
				$LogModel->where($condition)->delete();
			}
// 			Log::write($QRModel->getLastSql());
			return true;
		} else {
			return false;
		}
	}
	
	/*
	 * 获取临时可用的二维码id
	 */
	private function getMaxNotLimitSceneId($customerId) {
		$QRModel = M("qrcode");
		$where["deleted"] = 0;
		$where["fromCustomerId"] = $customerId;
		$where["actionName"] = QR_SCENE;
		$sceneId = $QRModel->where($where)->max("sceneId");
		if ($sceneId == NULL) {
			$sceneId = MAX_SCENEID + 1;
		} else {
			$sceneId = $sceneId + 1;
		}
		return $sceneId;
	}
	
	public function getAvailableSceneId() {
		$QRModel = M("qrcode");
		
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$customerId = Session::$user["customerId"];
		$where["deleted"] = 1;
		$where["fromCustomerId"] = $customerId;
		$where["actionName"] = QR_LIMIT_SCENE;
		$where["sceneId"] = array('exp', 'IS NOT NULL');
		
		$sceneId = $QRModel->where($where)->getField('sceneId');
		
		if ($sceneId == NULL) {
			// 被删除的数据sceneId不为空，被删除的数据且sceneId被复用的把sceneId设为NULL
			$condition['deleted'] = array('eq',0);
			$condition['actionName'] = array('eq',QR_LIMIT_SCENE);
			$condition['fromCustomerId'] = array('eq',$customerId);
			
			$sceneId = $QRModel->where($condition)->max("sceneId");
			
			if ($sceneId == NULL) {
				$sceneId = 1;
			} else if ($sceneId < MAX_SCENEID) {
				$sceneId = (int)$sceneId + 1;
			} else {
				Output::instance()->resultCode(code_qr_scene_no_invalid);
				return;
			}
		}
		Output::instance()->object($sceneId);
	}
	
	public function createQRCode($action_name, $sceneId, $expireSeconds = NULL) {
		$result = $this->createTicket($action_name, $sceneId, $expireSeconds);
		if ($result == NULL) {
			return NULL;
		} else if($result->errcode != 0) {
			if ($result->errcode == 48001) {
				Output::instance()->resultCode(code_userinfo_api_auth);
				return NULL;
			}
			Log::write('create qr error code:' . $result->errcode);
			Log::write($result->errmsg);
			Output::instance()->resultCode(code_qr_create_error, '二维码生成失败，' . $result->errmsg);
			return NULL;
		} else {
			return $result;
		}
	}
	
	private function createTicket($action_name, $sceneId, $expireSeconds) {
		$param["action_name"] = $action_name;
		$id["scene_id"] = (int)$sceneId;
		$scene["scene"] = $id;
		if ($action_name == QR_SCENE) {
			if ($expireSeconds == NULL) {
				$param["expire_seconds"] = QR_EXPIRE_SECONDS;
			} else {
				$param["expire_seconds"] = $expireSeconds;
			}
		}
		$param["action_info"] = $scene;
		$param = json_encode($param);
// 		Log::write($param);
		
		$access_token = WeixinApi::getAccessToken();
		if (!isset($access_token)) {
			return NULL;
		}
		
		$url='https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=' . $access_token;
		Log::write($url);
		
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_URL,$url);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $param);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		$result = curl_exec($ch);
		curl_close($ch);
// 		Log::write($result);
		$result = json_decode($result);
		return $result;
	}
	
	public function zeroClearScanCount($sceneId, $actionName = QR_LIMIT_SCENE) {
		$QRModel = M("qrcode");
		$QRLogModel = M("qrcode_scan_log");
		
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}

		$customerId = Session::$user['customerId'];
		
		$where["sceneId"] = $sceneId;
		$where["fromCustomerId"] = $customerId;
		$QRLogModel->where($where)->delete();
		
		$where["actionName"] = $actionName;
		$data["updateTime"] = date("Y-m-d H:i:s");
		$data["scanCount"] = 0;
		$data["scanUserCount"] = 0;
		$QRModel->where($where)->save($data);
		
		Output::instance()->resultCode();
	}
	
	public function getStatistics($startDate, $endDate, $module, $order = "updateTime", $orderBy = "desc", $start = 0, $limit = 25) {
		$QRLogModel = M("qrcode_scan_log");
		
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		
		$customerId = Session::$user["customerId"];
		$condition["log.fromCustomerId"] = $customerId;
		$condition["log.createTime"] = array("between","$startDate,$endDate");
		$condition["qr.deleted"] = 0;
		$condition["qr.actionName"] = QR_LIMIT_SCENE;
		if ($module != '') {
			$condition["qr.module"] = $module;
		}
		
		$arr = $QRLogModel->alias("log")
			->join("wx_qrcode qr ON log.sceneId = qr.sceneId AND log.fromCustomerId = qr.fromCustomerId")
			->where($condition)->field("qr.* , count(log.sceneId) as scanCount")->group("log.sceneId")
			->order("$order $orderBy")->limit("$start, $limit")->select();
// 		echo $QRLogModel->getLastSql();
		if ($arr) {
			$count = $QRLogModel->alias("log")->join("wx_qrcode qr ON log.sceneId = qr.sceneId") 
				->group("log.sceneId")->where($condition)->count("log.sceneId");
			Output::instance()->objArray($arr, $count);
		} else {
			Output::instance()->resultCode();
		}
	}
	
	
	public function createRouterQRCode($appId, $number, $token = '', $signStr = '') {
        /**
         * LLyeap_wx_customer修改
         * 这里通过appid进行筛选, 所以不需要mediaId
         */
        /***** LLyeap_delete *****/
//		$CustomerModel = M("customer");
//        $where["appid"] = $appId;
//		$customer = $CustomerModel->where($where)->find();
        /*****  *****/

		$IndMediaInfo_Model = M("ind_media_info");
		$where["appid"] = $appId;
		$customer = $IndMediaInfo_Model->where($where)->find();
		if (!$customer) {
			Output::instance()->resultCode(code_user_not_exist);
			return;
		}

        /***** LLyeap_delete *****/
//		$customerId = $customer["id"];
        /*****  *****/
		$customerId = $customer["cid"];
		Session::switchCustomer($customerId);
		
		$qrId = $this->addAfterSessionInit($number, '', QR_SCENE, '', module_handle_wxrouter, '');
		if ($qrId) {
			$QRModel = M("qrcode");
			$whereQR["id"] = $qrId;
			$qr = $QRModel->where($whereQR)->field("ticket, sceneId")->find();
			if (!$qr) {
				Output::instance()->resultCode(code_qr_not_exist);
				return;
			}
			$result["ticket"] = $qr["ticket"];
			$result["number"] = $qr["sceneId"];
			$result["qrcode"] = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket={$qr["ticket"]}"; 
			Output::instance()->object($result);
		}
	}
	
	
	
	public function getQRCodeType($order = "id", $orderBy = "desc",$start = 0, $limit = ''){
		if (!Session::init()) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$customerId = Session::$user["customerId"];
		Session::switchCustomer(0);
				
		$qrcodeRole= M("qrcode_type");
		$where["fromCustomerId"] = $customerId;
		if($limit==''){
			$arr=$qrcodeRole->where($where)->select();
		}else{
			$arr=$qrcodeRole->where($where)->order("$order $orderBy")->limit("$start, $limit")->select();
		}
		$count=$qrcodeRole->where($where)->count();
		Session::switchCustomer($customerId);
		if ($arr) {
			Output::instance()->objArray($arr,$count);
		} else {
			Output::instance()->resultCode(code_success);
		}
	}
	
	public function delQRCodeType($id){
		if (!Session::init()) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$customerId = Session::$user["customerId"];
		Session::switchCustomer(0);				
		$qrcodeRole= M("qrcode_type");
		$qrcodeRole->where("id='$id'")->delete();
		Session::switchCustomer($customerId);
		Output::instance()->resultCode(code_success);
	}
	
	public function updateQRCodeType($id,$typename){
		if (!Session::init()) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
	
		$customerId = Session::$user["customerId"];
		Session::switchCustomer(0);				
		$qrcodeRole= M("qrcode_type");
		$data['typename'] = $typename;
		$qrcodeRole->where("id=$id")->save($data);
		Session::switchCustomer($customerId);
		if ($arr) {
			Output::instance()->objArray($arr);
		} else {
			Output::instance()->resultCode(code_success);
		}
	}
	
	public function addQRCodeType($typename){
		if (!Session::init()) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
	
		$customerId = Session::$user["customerId"];
		Session::switchCustomer(0);				
		$qrcodeRole= M("qrcode_type");
		$where["fromCustomerId"] = $customerId;
		$where["typename"] = $typename;
		$arr=$qrcodeRole->where($where)->find();
		Session::switchCustomer($customerId);
		if(!$arr){
			$qrcodeRole->create();
			$qrcodeRole->typename = $typename;	
			$qrcodeRole->fromCustomerId = $customerId;
			$result = $qrcodeRole->add();
			if ($result) {
				Output::instance()->resultCode(code_success);
			} else {
				Output::instance()->resultCode(code_sql_error);
			}
		} else {
			Output::instance()->resultCode(code_success);
		}
	}
	
	
	public function getQRCodeTypeById($id){
		if (!Session::init()) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
	
		$customerId = Session::$user["customerId"];
		Session::switchCustomer(0);				
		$qrcodeRole= M("qrcode_type");
		$arr=$qrcodeRole->where("id=$id")->find();		
		Session::switchCustomer($customerId);
		if ($arr) {
			Output::instance()->object($arr);
		} else {
			Output::instance()->resultCode(code_success);
		}
	}
	
	
	
	
}